<template>
  <el-form :model="form" label-width="100px" class="form-container" style="margin-top: 100px">
    <el-row :gutter="20">
      <!-- 左侧栏 -->
      <el-col :span="8">
        <el-form-item label="单据编号：">
          <el-input
              v-model="form.code"
              placeholder="请输入"
              clearable
          />
        </el-form-item>

        <el-form-item label="单据阶段：">
          <el-select
              v-model="form.stage"
              placeholder="请选择"
              clearable
          >
            <el-option
                label="已生效"
                value="active"
                :checked="form.stage === 'active'"
            />
            <!-- 其他选项可根据需要添加 -->
          </el-select>
        </el-form-item>
      </el-col>

      <!-- 中间栏 -->
      <el-col :span="10">
        <el-form-item label="单据日期：">
          <el-date-picker
              v-model="form.dateRange"
              type="daterange"
              range-separator="至"
              :start-placeholder="form.dateRange[0] || '请选择开始'"
              :end-placeholder="form.dateRange[1] || 'A'"
          />
        </el-form-item>

        <el-form-item label="已作废：">
          <el-select v-model="form.invalid" placeholder="否">
            <el-option label="否" value="no" />
            <el-option label="是" value="yes" />
          </el-select>
        </el-form-item>



      </el-col>



      <!-- 右侧操作按钮 -->
      <el-col :span="6" class="action-buttons">
        <el-button type="primary" @click="handleQuery">查询</el-button>
        <el-button type="info" @click="handleReset">重置</el-button>
        <el-button type="success" @click="toggleCollapse">收</el-button>
      </el-col>

      <el-col :span="6">

        <el-form-item label="供应商" prop="pid">
          <el-select
              v-model="form.pid"
              placeholder="请选择供应商"
              style="width: 240px"
              clearable
              filterable
          >
            <el-option
                v-for="provider in providerList"
                :key="provider.id"
                :label="`${provider.code} - ${provider.name}`"
                :value="provider.id"
            />
          </el-select>
        </el-form-item>
      </el-col>

    </el-row>
  </el-form>

  <div>
    <BuyInStorePageUtil style="margin-top: 20px"
        :table-data="tableData"
        :columns="tableColumns"
        :current-page="pageNo"
        :total="total"
        :page-size="pageSize"
        @page-change="handlePageChange"
        @action="handleTableAction"
        @edit="updateInStore"
        @delete="del"
        @selection-change="handleSelectionChange"
                        @code-click="updateInStore"
                        @row-audit="handleRowAudit"
    ></BuyInStorePageUtil>

    <el-dialog
        v-model="auditDialogVisible"
        title="单据审核"
        width="600px"
        :close-on-click-modal="false"
    >
      <el-form :model="auditForm" :rules="auditRules" ref="auditFormRef">
        <el-form-item label="单据编号：" prop="code">
          <el-input
              v-model="auditForm.code"
              disabled
              placeholder="系统自动填充"
          />
        </el-form-item>

        <el-form-item label="审核人：" prop="auditor">
          <el-select
              v-model="auditForm.auditor"
              placeholder="请选择审核人"
              disabled
              filterable
              clearable
              style="width: 100%"
          >
            <el-option
                v-for="user in userList"
                :key="user.id"
                :label="`${user.name} `"
                :value="user.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="审批意见：" prop="comment">
          <el-input
              v-model="auditForm.comment"
              type="textarea"
              :rows="3"
              placeholder="请输入审批意见"
              maxlength="200"
              show-word-limit
          />
        </el-form-item>
        <el-form-item label="审核结果：" prop="checkResult">
          <el-select
              v-model="auditForm.checkRes"
              placeholder="请选择审核结果"
              style="width: 100%"
          >
            <el-option label="通过" :value="true" />
            <el-option label="不通过" :value="false" />
          </el-select>
        </el-form-item>

      </el-form>

      <template #footer>
        <el-button @click="auditDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAudit">提交审核</el-button>
      </template>
    </el-dialog>
    <input
        type="file"
        ref="fileInput"
        style="display: none"
        accept=".xlsx,.xls"
        @change="handleFileSelect"
    />
  </div>


</template>

<script setup lang="ts">
import { ref,reactive, toRaw } from 'vue';
import axios from 'axios';
import SalesOrderPage from '@/sales-order/SalesOrderPage.vue';
import { useRoute,useRouter } from 'vue-router';
import type { SalesOrder } from '@/types/public-xs/salesDocuments';
import { ElMessage } from 'element-plus';
import BuyInStorePageUtil from "@/kc-view/instore/buy-inStore/BuyInStorePageUtil.vue";
import TestPage from "@/test/TestPage.vue";
import type {User} from "@/types/rs/User.ts";
import request from "@/util/request.ts";
import type {PublicProvider} from "@/types/public-cg/provider.ts";

const fileInput = ref<HTMLInputElement | null>(null); // 文件输入框引用
let pageNo=ref(1)
let pageSize=ref(3)
let total=ref(0)
let route=useRoute()
let router=useRouter()
const form = reactive({
  code: '',
  providerName: '',
  pid:null,
  stage: 'active',
  dateRange: [],
  invalid: 'no',
  subject: ''
})
// 新增响应式数据
const auditDialogVisible = ref(false);
const auditFormRef = ref();
const auditForm = reactive({
  code: '',
  auditor: '',
  comment: '',
  checkRes: null
});

let userList=ref<User[]>([])
let selectUser=async()=>{
  let response=await request.post('per/user/getAll')
  userList.value=response.data.data
  console.log(userList.value)
}
selectUser()

// 1. 从 sessionStorage 获取存储的字符串
const storedData = sessionStorage.getItem("user");

if (storedData) {
  try {
    // 2. 解析 JSON 字符串 → 得到 { user: { id: 1, ... } } 结构
    const parsedData = JSON.parse(storedData);

    // 3. 访问嵌套的 user 对象
    const userObj = parsedData.user;

    // 4. 获取 user 的 id
    auditForm.auditor = userObj.id;
    console.log("用户ID:", userObj.id); // 输出：用户ID: 1

  } catch (error) {
    console.error("解析数据失败:", error);
  }
} else {
  console.warn("sessionStorage 中未找到 user 数据");
}

let providerList=ref<PublicProvider[]>([])
let selectProvider=async()=>{
  let response=await request.post('basic/Provider/selectAllSupplier')
  providerList.value=response.data.data
  console.log(providerList.value)
}
selectProvider()


// 表单验证规则
const auditRules = reactive({
  auditor: [{ required: true, message: '请选择审核人', trigger: 'change' }],
  comment: [{ required: true, message: '请输入审批意见', trigger: 'blur' }],
  checkRes: [{ required: true, message: '请选择审核结果', trigger: 'change' }]
});
// 审核方法
const handleRowAudit = (row: any) => {
  auditForm.code = row.code
  auditDialogVisible.value = true
  console.log('当前审核单据:', row.code)
}
const submitAudit = async () => {
  // 表单验证
  if (!await auditFormRef.value?.validate()) return;

  // const rawArray = toRaw(selectedDocs.value);
  // const docCodeValue = rawArray[0];


  try {
    const response = await request.post('kc/inStore/check', {
      code: auditForm.code,
      typeId: 5,
      status: 3,
      checkManId: auditForm.auditor,  // 绑定审核人ID
      checkComment: auditForm.comment, // 绑定审批意见
      checkRes: auditForm.checkRes // 绑定审核结果
    });
    let response1=await request.post('kc/inStore/getInStoreList',{
      code:auditForm.code,
      typeId:5
      // ...queryParams
    })

    let response2 = await request.post('kc/inStoreDetail/getInStoreDetailList', {
      inStoreCode:auditForm.code
    },{
      headers:{
        'Content-Type':'application/x-www-form-urlencoded'
      }
    });
    console.log(response1.data.data)
    console.log(response2.data.data)
  let sumCount = ref(0)
   if(response1.data.data.list[0].orderStatus==3){
     if(response2.data.data!=null&&response2.data.data.length>0){
       response2.data.data.forEach(item=>{
         let response4 = request.post('kc/StoreGoodSummary/method',{
               sid:item.storeId,
               gid:item.goodId,
               stock:item.count,
               sumCost:item.inStoreSumCost
             },
         )
         sumCount.value+=item.count
       })
     }
     console.log(response1.data.data.list[0])
     if(response1.data.data.list[0].sourceCode!=''&&response1.data.data.list[0].sourceCode!=null){

       let response5 = request.post('cg/CGDD/updateCGDDData',{
             code:response1.data.data.list[0].sourceCode,
             get_num:sumCount.value,
             wait_amount:-response1.data.data.list[0].inStoreSumPrice,
             get_amount:response1.data.data.list[0].inStoreSumPrice
           },
       )
     }
   }


    ElMessage.success('审核成功');
    auditDialogVisible.value = false;
    fetchData(pageNo.value); // 刷新表格数据
  } catch (error) {
    ElMessage.error('审核提交失败');
  } finally {
    // 重置表单
    auditForm.comment = '';
  }
};

const handleQuery = () => {
  // 重置为第一页
  pageNo.value = 1
  fetchData(pageNo.value)
  // 传递表单查询参数
  // fetchData(pageNo.value, {
  //   doCode: form.docNumber,
  //   stage: form.stage,
  //   invalid: form.invalid,
  //   startDate: form.dateRange[0] ? formatDate(form.dateRange[0]) : undefined,
  //   endDate: form.dateRange[1] ? formatDate(form.dateRange[1]) : undefined
  // })
}

const handleReset = () => {
  Object.assign(form, {
    docNumber: '',
    stage: 'active',
    dateRange: [],
    invalid: 'no',
    subject: ''
  })
}

const del=async (row: any) => {
  if (!confirm('你确定要删除吗？')) {
    return
  }
  let response = await request.get('kc/inStore/delInStore', {
    params:{
      id:row.id
    }
  })

  if(response.data.data){
    ElMessage.success('删除成功')
    pageNo.value=1
    await fetchData(pageNo.value)
  }else{
    ElMessage.error('删除失败')
  }



}

const toggleCollapse = () => {
  // 收起/展开逻辑
}

const tableColumns = ref([
    { prop: 'code', label: '单据编号', width: 200 },
    { prop: 'orderDate', label: '单据日期', width: 200 },
    { prop: 'sourceCode', label: '源单号', width: 200 },
    { prop: 'providerName', label: '供应商名称', width: 200 },
    { prop: 'deptName', label: '部门名称', width: 200 },
    { prop: 'businessmanName', label: '业务员名称', width: 200 },
    { prop: 'orderStatus', label: '单据状态', width: 200 },
    { prop: 'storeManName', label: '库管员名称', width: 200 },
    { prop: 'typeName', label: '业务类型', width: 200 },
    { prop: 'orderTypeId', label: '订单类型', width: 200 },
    { prop: 'inStoreSumPrice', label: '入库总价(元)', width: 200 },
    { prop: 'createName', label: '创建者名称', width: 200 },
    { prop: 'createDate', label: '创建日期', width: 200 },
    { prop: 'updateName', label: '更新者名称', width: 200 },
    { prop: 'updateDate', label: '更新日期', width: 200 }
])

let tableData=ref([])
const handlePageChange = (newPage: number) => {
  pageNo.value = newPage;
  fetchData(newPage);
}
// const formatDate = (date: Date, isEndDate: boolean = false) => {
//   const pad = (num: number) => num.toString().padStart(2, '0');
//   const year = date.getFullYear();
//   const month = pad(date.getMonth() + 1);
//   const day = pad(date.getDate());
//
//   // 如果是结束日期，时间设为 23:59:59
//   if (isEndDate) {
//     return `${year}-${month}-${day} 23:59:59`;
//   }
//   return `${year}-${month}-${day} 00:00:00`;
// };


const handleTableAction = (actionName: string,selectedRows?: any[]) => {
  switch(actionName){
    case 'add':
      router.push('/home/inStore/buyInStore/add')
      break
    case 'import':
      fileInput.value?.click();
      break
    case 'downLoadTemplate':
      handleDownloadTemplate()
        break
    case 'export':
      handleExport(selectedRows)
      break
    case'check':
      handleCheck()
      break;
  }
}

async function fetchData(page: number) {
  // const [startDate, endDate] = form.dateRange || []
  let params = {
    pageNo: page,
    pid:form.pid,
    pageSize: pageSize.value,
    code:form.code,
    providerName:form.providerName,
    typeId:5
    // doCode: form.docNumber,
    // stage: form.stage,
    // invalid: form.invalid,
    // startDate: startDate ? formatDate(startDate) : undefined,
    // endDate: endDate ? formatDate(endDate) : undefined
  }

  let response=await request.post('kc/inStore/getInStoreList',{
    ...params,
    // ...queryParams
  })
  tableData.value=response.data.data.list
  console.log(tableData.value)
  total.value=response.data.data.total

}
fetchData(1)
const updateInStore=(row: any)=>{
  router.push({
    name:'EditBuyInStore',
    params:{
      code: row.code // 传递单据编号
    }
  })

}

//导入方法
const handleFileSelect = async (event: Event) => {
  const input = event.target as HTMLInputElement;
  const file = input.files?.[0];
  if (!file) {
    ElMessage.warning('未选择文件');
    return;
  }

  // 校验文件后缀
  const allowedExtensions = ['.xlsx', '.xls'];
  const fileExtension = file.name.substring(file.name.lastIndexOf('.')).toLowerCase();
  if (!allowedExtensions.includes(fileExtension)) {
    ElMessage.error('文件格式不正确，仅支持 .xlsx 和 .xls 文件');
    input.value = ''; // 重置文件输入框
    return;
  }

  // 校验文件大小
  const maxFileSize = 10 * 1024 * 1024; //10MB
  if (file.size > maxFileSize) {
    ElMessage.error(`文件大小超过限制，最大允许10MB，当前文件大小'${file.size.toFixed(2)}MB'`);
    input.value = ''; //重置
    return;
  }

  const formData = new FormData();
  formData.append('file', file);

  // const loading = ElLoading.service({text: '正在导入...'});
  try {
    const response = await request.post('kc/inStore/import', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    });
    console.log(response.data.msg, ",", response.data.code)
    if (response.data.code === '200') {
      ElMessage.success('导入成功');
      await fetchData(pageNo.value); // 刷新表格数据
    } else {
      ElMessage.error(response.data.msg || "导入失败！");
    }
  }
  // catch (error) {
  //   ElMessage.error('导入失败，请稍后重试');
  //   console.log(error)
  // }
  finally {
    // loading.close();
    input.value = ''; // 重置文件输入框
    ElMessage.success('导入成功');
    await fetchData(pageNo.value); // 刷新表格数据
  }
};

//下载模板
const handleDownloadTemplate = async () => {
  try {
    const response = await request.get('kc/inStore/template', {
      responseType: 'blob',
    });
    console.log(response)
    const url = window.URL.createObjectURL(new Blob([response.data]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', '采购入库表.xlsx');
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    ElMessage.success('模板下载成功');
  } catch (error) {
    ElMessage.error('模板下载失败，请稍后重试');
  }
}

const selectedDocs = ref<string[]>([])

// 监听子组件选择事件
const handleSelectionChange = (selection: SalesOrder[]) => {
  selectedDocs.value = selection.map(row => row.docCode)
}

const importAction = () => {

}

//导出方法
const handleExport = async (selectedRows?: any[]) => {
  // 过滤掉前端添加的额外字段
  const filteredRows = selectedRows ? selectedRows.map(row => {
    // console.log(row)
    // //回显详情
    // let response2 =  axios({
    //   method: 'post',
    //   url: 'kc/inStoreDetail/getInStoreDetailList',
    //   data: {
    //     inStoreCode: row.code
    //   },
    //   headers: {
    //     'Content-Type': 'application/x-www-form-urlencoded'
    //   }
    // }).then(res=>{
    //   row.details = res.data.data
    // })1
    let {index, orderDate, createDate, updateDate, ...rest} = row;
    return rest;
  }) : [];
  console.log('过滤后的 filteredRows:', filteredRows);
  const params = {
    selectedRows: filteredRows || [] // 包含选中行
  };
  // const loading = ElLoading.service({text: "正在导出..."});
  try {
    const response = await request.post("kc/inStore/export", params, {
      responseType: "blob",
    });
    const url = window.URL.createObjectURL(new Blob([response.data]));
    const link = document.createElement("a");
    link.href = url;
    link.setAttribute("download", "采购入库信息表.xlsx");
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    ElMessage.success("导出成功");
  } catch (error) {
    console.error("导出失败:", error);
    ElMessage.error("导出失败，请稍后重试");
  } finally {
    // loading.close();
  }
};

// 审核方法
const handleCheck = async () => {
  if (selectedDocs.value.length === 0) {
    ElMessage.warning('请至少选择一条需要审核的单据')
    return
  }
  const rawArray = toRaw(selectedDocs.value);
  const docCodeValue = rawArray[0];

  try {

    const response = await request.post('kc/inStore/check', {
      code:docCodeValue,
      typeId:5,
    })
    ElMessage.success('审核成功')
    fetchData(pageNo.value) // 刷新数据

  } catch (error) {
    ElMessage.error('审核失败')
  }
}




</script>

<style scoped>

</style>
